package render;

import render.Primitive.Postion;
import geom.Geometry;

/**
 * sphere primitive
 * 
 * @author Robbe
 *
 */

public class Sphere implements Primitive {
	Material material;
	double radius;
	double[] position;
	double flip;
	
	public Sphere(double radius, double[] position, Material material, boolean flipNormals) {
		this.material = material;
		this.radius = radius;
		this.position = position;
		this.flip = flipNormals ? -1 : 1; 
	}
	
	public Sphere(double radius, double[] position, Material material) {
		this(radius, position, material, false);
	}
	
	public double intersection(double[] eye, double[] ray) {
		
		double[] r = Geometry.difference(eye, position);		
		
		double a = Geometry.dotProduct(ray, ray);
		double b = 2 * Geometry.dotProduct(ray, r);
		double c = Geometry.dotProduct(r, r) - radius*radius;
		
		double p = b / a;
		double q = c / a;
		
		double sqrt = Math.sqrt(Math.pow(p/2, 2) - q);
		
		if (sqrt == Double.NaN) {
			return Double.NaN;
		}
		
		double t1 = -p/2 - sqrt;
		double t2 = -p/2 + sqrt;		

		if (t1 >= RaytracerImage.tMin) {
			return t1;
		} 
		
		if (t2 >= RaytracerImage.tMin) {
			return t2;
		} 
			
		return Double.NaN;
	}
	

	public double[] getNormal(double[] p) {
		// TODO Auto-generated method stub
		return Geometry.product(Geometry.difference(p,position),flip/radius);
	}

	public Postion inHalfSpace(double m, int axis) {
		// TODO Auto-generated method stub
		return Postion.BOTH;
	}
	
	public double[] getPostion() {
		// get center point of sphere
		return position;
	}
	
	public Material getMaterial() {
		return material;
	}
}
